package com.ruoyi.reim.service;

import com.ruoyi.activiti.domain.dto.WorkflowTrajectory;
import com.ruoyi.activiti.service.impl.WorkflowTrajectoryService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.external.domain.ReimDomain;
import com.ruoyi.reim.domain.WorkflowReim;
import com.ruoyi.reim.domain.WorkflowReimDetail;
import com.ruoyi.reim.mapper.WorkflowReimMapper;
import com.ruoyi.system.service.ISysUserService;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 报销基本信息Service业务层处理
 *
 * @author ruoyi
 * @date 2021-07-16
 */
@Service
public class WorkflowReimService
{
    @Autowired
    private WorkflowReimMapper workflowReimMapper;

    @Autowired
    private WorkflowReimDetailService workflowReimDetailService;

    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private WorkflowTrajectoryService workflowTrajectoryService;

    /**
     * 查询审批详情
     * @param id
     * @return
     */
    public Map<String, Object> selectApproveDetail(String id){
        Map<String, Object> map = new HashMap<>();
        map.put("summaryInfo", workflowReimMapper.selectWorkflowReimById(id));
        WorkflowReimDetail workflowReimDetail = new WorkflowReimDetail();
        workflowReimDetail.setrId(id);
        map.put("detailInfo", workflowReimDetailService.selectWorkflowReimDetailList(workflowReimDetail));
        WorkflowTrajectory workflowTrajectory = new WorkflowTrajectory();
        workflowTrajectory.settId(id);
        map.put("trajectoryInfo", workflowTrajectoryService.selectWorkflowTrajectoryList(workflowTrajectory));
        return map;
    }

    /**
     * 查询报销基本信息
     *
     * @param id 报销基本信息ID
     * @return 报销基本信息
     */
    public WorkflowReim selectWorkflowReimById(String id)
    {
        return workflowReimMapper.selectWorkflowReimById(id);
    }

    /**
     * 查询报销基本信息列表
     *
     * @param workflowReim 报销基本信息
     * @return 报销基本信息
     */
    public List<WorkflowReim> selectWorkflowReimList(WorkflowReim workflowReim)
    {
        return workflowReimMapper.selectWorkflowReimList(workflowReim);
    }

    /**
     * 新增报销
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int reim(ReimDomain reimDomain){

//        SysUser sysUser = new SysUser();
//        sysUser.setUserId(Long.parseLong(reimDomain.getEmployee()));
//        List<SysUser> userList = sysUserService.selectUserList(sysUser);
//        if(userList.isEmpty()){
//            return 0;
//        }

        // 生成基本信息ID
        String id = UUID.randomUUID().toString();
        // 获取明细
        List<WorkflowReimDetail> list = reimDomain.getDetailList();
        // 设置创建人
        reimDomain.setCreateBy(SecurityUtils.getUsername());
        reimDomain.setCreateTime(DateUtils.getNowDate());
        list.stream().forEach(item->{
            item.setCreateBy(SecurityUtils.getUsername());
            item.setCreateTime(DateUtils.getNowDate());
            item.setrId(id);
        });

        //设置id
        reimDomain.setId(id);
        reimDomain.setTitle("财务员工报销流程");
        // 获取提交人信息

        // 获取一级审批人信息
        String join = StringUtils.join(sysUserService.selectUserNameByPostCodeAndDeptId("cwbz", SecurityUtils.getLoginUser().getUser().getDeptId()), ",");
        // 启动工作流
        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey("reimApprove")
                .withName(reimDomain.getTitle())
                .withBusinessKey(id)
                .withVariable("deptLeader",join)
                .build());

        // 设置流程实例id
        reimDomain.setInstanceId(processInstance.getId());
        // 保存基本信息与明细信息
        reimDomain.setState("2");
        workflowReimMapper.insertWorkflowReim(reimDomain);
        // 添加一条轨迹信息
        WorkflowTrajectory workflowTrajectory = new WorkflowTrajectory();
        workflowTrajectory.settId(id);
        workflowTrajectory.setBillCode(reimDomain.getBillCode());
        workflowTrajectory.setType("reimApprove");
        workflowTrajectory.setInstanceId(processInstance.getId());
        workflowTrajectory.setApprovalStatus("待审批");
        workflowTrajectory.setApprovalNodeName("财务部长审批");
        // 获取审批人姓名和邮箱
        List<SysUser> approvalList = sysUserService.selectApprovalInfo("cwbz", SecurityUtils.getLoginUser().getUser().getDeptId());
        String names = "";
        String emails = "";
        for(int i = 0, len = approvalList.size(); i < len; i++){
            names += approvalList.get(i).getNickName();
            emails += approvalList.get(i).getEmail();

            if(i < (len - 1)){
                names += ",";
                emails += ",";
            }
        }
        workflowTrajectory.setApprovalName(names);
        workflowTrajectory.setApprovalEmail(emails);
        workflowTrajectory.setStartTime(new Date());
        workflowTrajectory.setCreateTime(new Date());
        workflowTrajectory.setCreateBy(SecurityUtils.getUsername());
        workflowTrajectory.setFirst(true);
        workflowTrajectoryService.insertWorkflowTrajectory(workflowTrajectory);
        // 保存明细信息
        return workflowReimDetailService.saveList(list);
    }

    /**
     * 新增报销基本信息
     *
     * @param workflowReim 报销基本信息
     * @return 结果
     */
    public int insertWorkflowReim(WorkflowReim workflowReim)
    {
        workflowReim.setCreateTime(DateUtils.getNowDate());
        return workflowReimMapper.insertWorkflowReim(workflowReim);
    }

    /**
     * 修改报销基本信息
     *
     * @param workflowReim 报销基本信息
     * @return 结果
     */
    public int updateWorkflowReim(WorkflowReim workflowReim)
    {
        workflowReim.setUpdateTime(DateUtils.getNowDate());
        return workflowReimMapper.updateWorkflowReim(workflowReim);
    }

    /**
     * 批量删除报销基本信息
     *
     * @param ids 需要删除的报销基本信息ID
     * @return 结果
     */
    public int deleteWorkflowReimByIds(Integer[] ids)
    {
        return workflowReimMapper.deleteWorkflowReimByIds(ids);
    }

    /**
     * 删除报销基本信息信息
     *
     * @param id 报销基本信息ID
     * @return 结果
     */
    public int deleteWorkflowReimById(Integer id)
    {
        return workflowReimMapper.deleteWorkflowReimById(id);
    }
}
